#include <stdlib.h>
#include <string.h>
#include <iostream>

using std::cout;
using std::endl;

//拿到类外来了之后，就表明是普通函数，不是成员函数
void *operator new(size_t sz)
{
    cout << "void *operator new(size_t )" << endl;
    void *pret = malloc(sz);
    return pret;
}

void operator delete(void *pst)
{
    /* this;//error */
    cout << "void operator delete(void *)" << endl;
    free(pst);
}

class Student
{
public:
    Student(int id, const char *name)
    : _id(id)
    , _name(new char[strlen(name) + 1]())
    {
        cout << "Student(int, const char *)" << endl;
        strcpy(_name, name);
    }

#if 0
    static void *operator new(size_t sz)
    {
        cout << "void *operator new(size_t )" << endl;
        void *pret = malloc(sz);
        return pret;
    }

    static void operator delete(void *pst)
    {
        /* this;//error */
        cout << "void operator delete(void *)" << endl;
        free(pst);
    }
#endif

    void print() const
    {
        if(_name)
        {
            cout << "_id = " << this->_id << endl
                 << "_name = " << _name << endl;
        }
    }

    ~Student()
    {
        cout <<"~Student()" << endl;
        if(_name)
        {
            delete [] _name;
            _name = nullptr;
        }
    }
private:
    int _id;
    char *_name;
};

void test()
{
    //1、对象销毁与析构函数的执行是不是等价的？
    Student *pstu = new Student(4201, "xiaohong");
    pstu->print();

    delete pstu;
    pstu = nullptr;
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

